﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ClassLibrary.DAO;
using ClassLibrary.Entity;
using System.Collections;
using mprsc.Reports;
namespace mprsc
{
    public partial class Purchase : Form
    {
        TblCustomersDAO cusDAO = new TblCustomersDAO(Global.CONNECTION_STRING);
        TblPhoneBranDAO BrandDAO = new TblPhoneBranDAO(Global.CONNECTION_STRING);
        TblProductsDAO productDAO = new TblProductsDAO(Global.CONNECTION_STRING);
        TblModelDAO modelDAO = new TblModelDAO(Global.CONNECTION_STRING);
        TblProductsDAO itemsDAO = new TblProductsDAO(Global.CONNECTION_STRING);
        TblBookingDAO orderDAO = new TblBookingDAO(Global.CONNECTION_STRING);

        DataTable dt = null;

        public delegate void SendMessage(string Message);
        public SendMessage Sender;

        public Purchase()
        {
            InitializeComponent();
            //Tao con tro toi hàm GetMessage
            Sender = new SendMessage(GetMessage);
        }
        //Hàm có nhiem vu lay tham so truyen vào
        private void GetMessage(string Message)
        {
            label17.Text = Message;
        }

        // load customer detail
        private void LoadCustomerDetail()
        {
            DataTable dt = cusDAO.GetCustomerId(Global.ConvertToInt(label17.Text));
            foreach (DataRow dr in dt.Rows)
            {
                txtCustomerName.Text = dr["CustomerFullName"].ToString();
                txtCompanyName.Text = dr["CompanyName"].ToString();
                txtContactNo.Text = dr["phonemobile"].ToString();
            }

        }

        private void Purchase_Load(object sender, EventArgs e)
        {
            dateTimePicker1.Focus();
            this.CenterToScreen();
            LoadSale();
            LoadFactory();
            LoadProduct();
            CreateDataTable();
            if (dt.Rows.Count > 0)
            {
                btnDelete.Enabled = true;
            }
            else
            {
                btnDelete.Enabled = false;
            }

            if (label17.Text != "")
            {
                LoadCustomerDetail();

            }
            else
            {
            }
        }
        // load sale rep
        private void LoadSale()
        {
            cbSaleRep.DataSource = cusDAO.GetStaffList(1);
            cbSaleRep.DisplayMember = "CustomerFirstname";
            cbSaleRep.ValueMember = "CustomerIndex";
        }

        // Load Manufactory
        private void LoadFactory()
        {
            cbManufacture.DataSource = BrandDAO.GetAll();
            cbManufacture.ValueMember = "IDBrand";
            cbManufacture.DisplayMember = "BrandName";
        }

        // load Product 
        private void LoadProduct()
        {
            cbDescription.DataSource = productDAO.GetAllProduct();
            cbDescription.ValueMember = "ProductID";
            cbDescription.DisplayMember = "ProductName";
        }

        // load product By Model, Factory
        private void LoadProduct_ByModelFac()
        {
            if (cbModel.Text == "" || cbManufacture.Text == "")
            {
            }
            else
            {
                cbDescription.DataSource = productDAO.GetProductsList_ByID(2, Global.ConvertToInt(cbModel.SelectedValue.ToString()), Global.ConvertToInt(cbManufacture.SelectedValue.ToString()), txtProductType.Text.Trim(), 1);
                cbDescription.ValueMember = "ProductID";
                cbDescription.DisplayMember = "ProductName";
            }
        }

        private void txtProductType_TextChanged(object sender, EventArgs e)
        {
                cbDescription.DataSource = productDAO.GetProductsList_ByID(2, 0, 0, txtProductType.Text.Trim(), 2);
                cbDescription.ValueMember = "ProductID";
                cbDescription.DisplayMember = "ProductName";
        }

        private void cbManufacture_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataTable dt = modelDAO.GetModelByIdBrand(Global.ConvertToInt(cbManufacture.SelectedValue.ToString()));
            if (dt.Rows.Count > 0)
            {

                cbModel.DataSource = modelDAO.GetModelByIdBrand(Global.ConvertToInt(cbManufacture.SelectedValue.ToString()));
                cbModel.DisplayMember = "Model";
                cbModel.ValueMember = "IDModel";
            }
            else
            {
                cbModel.Text = "";
                cbDescription.Text = "";
            }
        }

        private void cbModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadProduct_ByModelFac();
        }

        private void cbDescription_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataTable product = productDAO.GetProductById(Global.ConvertToInt(cbDescription.SelectedValue.ToString()));
            foreach (DataRow dr in product.Rows)
            {
                //RRP: giá bán ra
                txtUnitPrice.Text = dr["RRP"].ToString();
            }
        }

        private void txtQuantity_TextChanged(object sender, EventArgs e)
        {
            int Quantity;
            decimal Price;
            decimal TotalPrice;
            Quantity = Global.ConvertToInt(txtQuantity.Text);
            Price = decimal.Parse(txtUnitPrice.Text);
            TotalPrice = Quantity * Price;
            txtExtPrice.Text = TotalPrice.ToString();
        }

        private void txtGST_TextChanged(object sender, EventArgs e)
        {
            if (txtGST.Text != "0" && lbAmountTotal.Text !="")
            {
                decimal Total_Price;
                Total_Price = decimal.Parse(lbAmountTotal.Text);

                int GST = 0;
                GST = Global.ConvertToInt(txtGST.Text);
                decimal Total;
                Total = Total_Price - (Total_Price * GST / 100);
                lbAmountTotal.Text = Total.ToString();
            }
        }
        public void CreateDataTable()
        {
            dt = new DataTable();
            DataColumn dc1 = new DataColumn("ProductID");
            DataColumn dc2 = new DataColumn("ProductName");
            DataColumn dc3 = new DataColumn("Price");
            DataColumn dc4 = new DataColumn("Quantity");
            DataColumn dc5 = new DataColumn("TotalPrice");

            dt.Columns.Add(dc1);
            dt.Columns.Add(dc2);
            dt.Columns.Add(dc3);
            dt.Columns.Add(dc4);
            dt.Columns.Add(dc5);
        }
        private void btnInsertCart_Click(object sender, EventArgs e)
        {
            try
            {
                TblBookingDetail order_detail = new TblBookingDetail();
                TblProducts item = itemsDAO.GetProductByIDProduct(int.Parse(cbDescription.SelectedValue.ToString()));
                order_detail.IdOrder = 1;
                order_detail.ProductId = item.ProductID;
                order_detail.Items = item;
                order_detail.Quantity = 1;
                order_detail.UnitPrice = item.RRP;
                order_detail.ProductName = item.ProductName;
          
                DataRow dr;
                do
                {
                    dr = dt.NewRow();
                    dr[0] = item.ProductID;
                    dr[1] = item.ProductName;
                    dr[2] = txtUnitPrice.Text;
                    dr[3] = txtQuantity.Text; 
                    dr[4] = txtExtPrice.Text;
                    dt.Rows.Add(dr); 
                }
                while (txtQuantity.Text == "" || txtUnitPrice.Text == "");
                grdCart.DataSource = dt;

                grdCart.Columns["ProductName"].Width = 300;
                grdCart.Columns["Price"].Width = 150;
                grdCart.Columns["TotalPrice"].Width = 150;


                decimal lbTotal = 0;

                if (grdCart.Rows.Count > 0)
                {
                    for (int i = 0; i < grdCart.Rows.Count; i++)
                    {
                       lbTotal += Convert.ToDecimal(grdCart[4, i].Value.ToString());
                    }
                }

                lbAmountTotal.Text = lbTotal.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            } 
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {          
            grdCart.Rows.Remove(dr);           
        }

        DataGridViewRow dr;
        private void grdCart_SelectionChanged(object sender, EventArgs e)
        {
            dr = new DataGridViewRow();
            foreach (DataGridViewRow drow in grdCart.SelectedRows)
            {
                dr = drow;
            }
            if (grdCart.SelectedRows.Count > 0)
            {
                btnDelete.Enabled = true;
            }
            else
            {
                btnDelete.Enabled = false;
            }


        }

        public void LoadDetail()
        {
            LoadProduct_ByModelFac();

            string idCus = label17.Text;
            DataTable customer = cusDAO.GetCustomerId(Global.ConvertToInt(idCus));
            foreach (DataRow dr in customer.Rows)
            {
                txtCompanyName.Text = dr["Companyname"].ToString();
                txtContactNo.Text = dr["phonemobile"].ToString();
                txtCustomerName.Text = dr["CustomerFullname"].ToString();
            }
            // noi dung booking
            DataTable dt = orderDAO.GetBook_ByIDCustomer(Global.ConvertToInt(idCus));

            foreach (DataRow dr in dt.Rows)
            {

               // decimal discount = Convert.ToInt32(dr["Discount"].ToString());
                //decimal total = Convert.ToDecimal(dr["Total"].ToString());
               // txtGST.Text = discount.ToString("c");
                //lbAmountTotal.Text = total.ToString("c");
                txtGST.Text = dr["Discount"].ToString();
                lbAmountTotal.Text = dr["Total"].ToString();
                txtOrderID.Text = dr["IDOrder"].ToString();

                dateTimePicker1.Text = Convert.ToDateTime(dr["OrderDate"]).ToShortDateString();

                txtExtPrice.Text = dr["ExtendPrice"].ToString();
                txtUnitPrice.Text = dr["UnitPrice"].ToString();

            }

            string idB = txtOrderID.Text;
            //grdCart.DataSource = orderDAO.GetBookByID(Global.ConvertToInt(idB), Convert.ToInt32(idCus));
            
           
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (txtCustomerName.Text == "" || txtContactNo.Text == "")
            {
                this.validationProvider1.ValidationMessages(!this.validationProvider1.Validate());
            }
            else
            {
                // insert customer
                TblCustomers cus = new TblCustomers();
                cus.CustomerFullname = txtCustomerName.Text;
                cus.Companyname = txtCompanyName.Text;
                cus.Phonemobile = txtContactNo.Text;
                cus.DateCreated = DateTime.Now;
                cus.IsAdmin = false;
                cus.CustomerTitle = "";
                cus.CustomerFirstname = "";
                cus.CustomerLastname = "";

                cus.Postalnumber = "";
                cus.Postalstreet = "";

                cus.Postalsuburb = "";
                cus.Postalpostcode = "";
                cus.Postalstate = "";
                cus.Phonework = txtContactNo.Text;
                cus.Phonehome = txtContactNo.Text;

                cus.Phonefacsimile = "";
                cus.Emailaddress = "";
                cus.Emailpassword = "";
                cus.PreferContactMethod = 1;

                if (label17.Text == "")
                {
                    cus.CustomerIndex = 0;
                    cusDAO.InsUpdCustomers(cus, 1);

                    DataTable dt = cusDAO.getCustomer_New();
                    int idCus = 0;
                    foreach (DataRow dr in dt.Rows)
                    {
                        idCus = Global.ConvertToInt(dr["CustomerIndex"].ToString());
                    }
                    label17.Text = idCus.ToString();
                }
                // insert booking
                TblBookingDAO orderdao = new TblBookingDAO(Global.CONNECTION_STRING);
                TblBooking order = new TblBooking();
                order.SaleRep = cbSaleRep.Text;
                order.OrderDate = DateTime.Now;
                order.ShipTo = "Name: " + " " + txtCustomerName.Text + "." + "Contact: " + txtContactNo.Text;
                order.CustomerIndex = Global.ConvertToInt(label17.Text);

                order.Total = Convert.ToDecimal(lbAmountTotal.Text);
                int id;
                orderdao.Insert(order, out id);

                TblBookingDetail detail = new TblBookingDetail();
                for (int i = 0; i < grdCart.Rows.Count; i++)
                {
                    detail.ProductId = Global.ConvertToInt(grdCart.Rows[i].Cells["ProductID"].Value.ToString());
                    detail.ProductName = grdCart.Rows[i].Cells["ProductName"].Value.ToString();
                    detail.IdOrder = id;
                    detail.Quantity = Global.ConvertToInt(grdCart.Rows[i].Cells["Quantity"].Value.ToString());
                    detail.UnitPrice = Convert.ToDecimal(grdCart.Rows[i].Cells["Price"].Value.ToString());
                    detail.ToatalAmount = Convert.ToDecimal(grdCart.Rows[i].Cells["TotalPrice"].Value.ToString());
                    detail.Discount = Global.ConvertToInt(txtGST.Text);
                    detail.ExtendPrice = Convert.ToDecimal(grdCart.Rows[i].Cells["Price"].Value.ToString());

                    orderdao.InsertBookingDetail(detail);
                }

                //this.Hide();
                //Purchase pc = new Purchase();
                //pc.Sender(idCus);
                //pc.Show();
                txtOrderID.Text = id.ToString();
                //DataTable dt = cusDAO.GetCustomerId(Global.ConvertToInt(idCus));
                LoadDetail();
               
               
              
            }

        }

        private void txtGST_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
                e.Handled = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (label17.Text == "")
            {
            }
            else
            {
                DataTable data = orderDAO.GetBook_ByIDCustomer(Global.ConvertToInt(label17.Text));

                var report = new CrystalReport6();

                report.SetDataSource(data);

                var reportViewer = new ReportViewer();

                reportViewer.SetReport(report);

                reportViewer.Show(this);

            }
        }

        //public DataSet impr(DataTable table)
        //{
        //    DataSet ds = new DataSet();
        //    ds.Tables.Add(table);
        //    ds.WriteXml(@"D:\test.xml");
        //    return ds;
        //}
    }
}
